package com.zgc.view.common;

import com.jfoenix.animation.alert.JFXAlertAnimation;
import com.jfoenix.controls.JFXAlert;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialogLayout;
import com.jfoenix.controls.JFXTextArea;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.image.Image;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.springframework.stereotype.Component;

@Component
public class DeleteAlertCtrl {

    private JFXAlert<String> alert;
    private JFXTextArea messageArea;
    private final Text titleText = new Text();
    private final JFXButton deleteButton = new JFXButton("确定删除");
    private final JFXDialogLayout jfxDialogLayout = new JFXDialogLayout();

    private void initialize() {
        if (alert == null) {
            alert = new JFXAlert<>();
            messageArea = new JFXTextArea();
            messageArea.setFont(Font.font(12));
            messageArea.setEditable(false);
            messageArea.setWrapText(true);
            messageArea.setPadding(new Insets(20));
            jfxDialogLayout.setHeading(titleText);
            jfxDialogLayout.setBody(messageArea);
            jfxDialogLayout.setActions(deleteButton);

            alert.setContent(jfxDialogLayout);
            setIcons("/view/images/icon.png");
            alert.setAnimation(JFXAlertAnimation.BOTTOM_ANIMATION);
        }
    }

    public JFXDialogLayout getRoot() {
        return jfxDialogLayout;
    }


    public void setMessageAndShow(String alertTitle, String messageTitle, String[] messages, EventHandler<ActionEvent> value) {
        initialize();
        defaultAlert();
        alert.setTitle(alertTitle);
        titleText.setText(messageTitle);
        for (String message : messages) {
            messageArea.appendText(message + "\n");
        }
        deleteButton.setOnAction(value);
        show();
    }

    public void show() {
        if (alert != null) {
            alert.show();
        }

    }

    public void close() {
        if (alert != null) {
            alert.close();
        }
    }

    public DeleteAlertCtrl setIcons(String iconsPath) {
        Stage window = (Stage) alert.getDialogPane().getScene().getWindow();
        window.getIcons().add(new Image(iconsPath));
        return this;
    }

    private void defaultAlert() {
        alert.setTitle(null);
        titleText.setText(null);
        messageArea.clear();
    }
}
